import base64
from typing import Union

from PyQt5.QtCore import QByteArray
from PyQt5.QtWidgets import QMessageBox
from fastapi import APIRouter
from pydantic import BaseModel
from func import imgs
from db.db_work import MysqlLite
router = APIRouter()


online_users=[]
class Register(BaseModel):
    username: str
    email: str
    password:str
    is_admin:bool

class Login(BaseModel):
    username: str
    password: str
    is_admin: bool

class User_date(BaseModel):
    old_username: str
    new_username: str
    email: str
    password: str
    avatar: str

@router.post('/register')
def register(register:Register):
    username = register.username
    email = register.email
    password = register.password
    is_admin = register.is_admin
    with open(r'./static/img/默认头像.png', 'rb') as f:
        avatar = f.read()
    avatar = imgs.resize_(avatar,128,128)
    avatar = QByteArray(avatar)
    my_sqlite=MysqlLite()
    my_sqlite.operation_sql("create table if not exists user_info(ID integer primary Key AUTOINCREMENT,username text,email text,password text,is_admin bool,blacklist bool,avatar BLOB)")
    user_name_exit=my_sqlite.exit_(f"select * from user_info where username=?",(username,))
    if user_name_exit:
        return {
            'code' : 400,
            'msg' :'账号已存在',
        }
    else:
        my_sqlite.operation_sql(f"insert into user_info (username,email,password,is_admin,blacklist,avatar)values(?,?,?,?,?,?)",(username,email,password,is_admin,False,avatar))
        return {
            'code' : 200,
            'msg' :'注册成功'
        }

@router.post('/login')
def login(login:Login):
    username = login.username
    password=login.password
    is_admin=login.is_admin
    my_sqlite=MysqlLite()
    my_sqlite.operation_sql("create table if not exists user_info(ID integer primary Key AUTOINCREMENT,username text,email text,password text,is_admin bool,blacklist bool,avatar BLOB)")
    user_name_exit=my_sqlite.select_sql(f"select * from user_info where username=? and password=? and is_admin=?",(username,password,is_admin))
    if user_name_exit:
        if user_name_exit[0][5] == 1:
            black=my_sqlite.select_sql("select * from blacklist where user_id1=? and exit=TRUE",(user_name_exit[0][0],))[0]
            lis=my_sqlite.select_sql('select username,email from user_info where ID=?',(black[6],))[0]
            text=f'你已被拉黑:起始时间{black[1]}，结束时间{black[2]}\n原因{black[3]}\n如有疑问联系{lis[0]},他的邮箱：{lis[1]}'
            return {
                'code' : 400,
                'msg': text
            }
        if username not in online_users:
            return {
                'code': 200,
                'msg': '登录成功',
            }
        else:
            return {
                'code': 400,
                'msg':'用户已登录'
            }
    else:
        return {
            'code': 400,
            'msg': '账号或密码错误'
        }

@router.get('/get_user')
def get_user(user_name:str):
    mysqlite=MysqlLite()
    exit=mysqlite.exit_(f"select * from user_info where username=?",(user_name,))
    if exit:
        user=mysqlite.select_sql(f"select * from user_info where username=?",(user_name,))[0]
        user_id=user[0]
        user_email=user[2]
        user_avatar=base64.b64encode(user[6]).decode('utf-8')
        is_blacklist=user[5]
        return {
            'code': 200,
            'data': {
                'user_id': user_id,
                'email': user_email,
                'avatar': user_avatar,
                'is_blacklist': is_blacklist,
            }
        }
    else:
        return {
            'code': 400,
            'msg':'用户不存在'
        }
@router.put('/update_user')
def update_user(user:User_date):
    mysqlite=MysqlLite()
    old_username=user.old_username
    new_username=user.new_username
    email=user.email
    password=user.password
    avatar = base64.b64decode(user.avatar)
    avatar = QByteArray(imgs.resize_(avatar, 128, 128))
    if new_username != old_username:
        exit=mysqlite.exit_("select * from user_info where username=?",(new_username,))
    else:
        exit=False
    if exit:
        return {
            'code': 400,
            'msg' : '用户名已存在'
        }
    else:
        mysqlite.operation_sql("update user_info set username=?,email=?,password=?,avatar=? where username=?",(new_username,email,password,avatar,old_username))
        mysqlite.operation_sql("update shops set sellername=? where sellername=?",(new_username,))
        return {
            'code': 200,
            'msg' : '修改成功'
        }
@router.get('/get_all_user')
def get_all_user():
    data=[]
    mysqlite=MysqlLite()
    mysqlite.operation_sql("create table if not exists user_info(ID integer primary Key AUTOINCREMENT,username text,email text,password text,is_admin bool,blacklist bool,avatar BLOB)")
    users_lis=mysqlite.select_sql("select * from user_info where is_admin=0")
    for user in users_lis:
        users={}
        users['userid']=user[0]
        users['username']=user[1]
        users['email']=user[2]
        users['password']=user[3]
        users['blacklist']=user[5]
        users['avatar']=base64.b64encode(user[6]).decode('utf-8')
        data.append(users)
    return {
        'code': 200,
        'data': data
    }
#date1为开始日期,date2为截止日期，user1id为用户id,user2id为管理员id
class Blacklist(BaseModel):
    date1 : Union[str,None]=None
    date2 : Union[str,None]=None
    reason: Union[str,None]=None
    user1id: int
    user2id: Union[int,None]=None,
    statu: bool
@router.put('/update_blacklist')
def update_blacklist(blacklist:Blacklist):
    date1=blacklist.date1
    date2=blacklist.date2
    reason=blacklist.reason
    user1id=blacklist.user1id
    user2id=blacklist.user2id
    status=blacklist.statu
    mysqlite=MysqlLite()
    mysqlite.operation_sql("update user_info set blacklist=? where ID=?",(status,user1id))
    mysqlite.operation_sql("""CREATE TABLE IF NOT EXISTS blacklist (
        ID INTEGER PRIMARY KEY AUTOINCREMENT,
        dated_at1 TEXT DEFAULT CURRENT_TIMESTAMP,
        dated_at2 TEXT DEFAULT CURRENT_TIMESTAMP,
        reason TEXT,
        exit bool,
        user_id1 INTEGER,
        user_id2 INTEGER,
        FOREIGN KEY (user_id1) REFERENCES user_info(ID) ON DELETE CASCADE,
        FOREIGN KEY (user_id1) REFERENCES user_info(ID) ON DELETE CASCADE
    );""")
    mysqlite.operation_sql("create table if not exists shops (ID integer primary Key AUTOINCREMENT,shop_name text,sellername text,price float,brand text,category text,description text,avatar BLOB,num int,exit bool,user_id INTEGER,FOREIGN KEY (user_id) REFERENCES user_info(ID) ON DELETE CASCADE)")
    if status==True:
        mysqlite.operation_sql("insert into blacklist (dated_at1,dated_at2,reason,exit,user_id1,user_id2) values (?,?,?,TRUE,?,?)",(date1,date2,reason,user1id,user2id))
        mysqlite.operation_sql("update shops set exit=2 where user_id=? and exit !=3",(user1id,))
    else:
        mysqlite.operation_sql("update blacklist set exit=False where user_id1=? and exit=True",(user1id,))
        mysqlite.operation_sql("update shops set exit=1 where user_id=? and num>0", (user1id,))
        mysqlite.operation_sql("update shops set exit=0 where user_id=? and num=0", (user1id,))
    return {
        'code': 200,
        'msg' : '修改成功'
    }

class Message(BaseModel):
    sender_id: int
    receiver_id: int
    message: str
    datetime: str



#用户发送消息
@router.post('/send_chat')
def chat(message:Message):
    user1_id=message.sender_id
    user2_id=message.receiver_id
    mes=message.message
    data=message.datetime
    mysql=MysqlLite()
    mysql.operation_sql("""CREATE TABLE IF NOT EXISTS history_message (
        ID INTEGER PRIMARY KEY AUTOINCREMENT,
        dated_at TEXT DEFAULT CURRENT_TIMESTAMP,
        message TEXT,
        user_id1 INTEGER,
        user_id2 INTEGER,
        FOREIGN KEY (user_id1) REFERENCES user_info(ID) ON DELETE CASCADE,
        FOREIGN KEY (user_id1) REFERENCES user_info(ID) ON DELETE CASCADE
    );""")
    mysql.operation_sql('insert into history_message (dated_at,message,user_id1,user_id2)values (?,?,?,?)',(data,mes,user1_id,user2_id))

#获取用户息西
@router.get('/get_chat')
def get_chat(user1 : int,user2 : int):
    mysql=MysqlLite()
    mysql.operation_sql("""CREATE TABLE IF NOT EXISTS history_message (
        ID INTEGER PRIMARY KEY AUTOINCREMENT,
        dated_at TEXT DEFAULT CURRENT_TIMESTAMP,
        message TEXT,
        user_id1 INTEGER,
        user_id2 INTEGER,
        FOREIGN KEY (user_id1) REFERENCES user_info(ID) ON DELETE CASCADE,
        FOREIGN KEY (user_id1) REFERENCES user_info(ID) ON DELETE CASCADE
    );""")
    data=mysql.select_sql("select user_id1,user_id2,dated_at,message from history_message where (user_id1=? and user_id2=?) or (user_id1=? and user_id2=?)",(user1,user2,user2,user1))
    return {
        'code': 200,
        'data': data
    }

#删除消息
@router.delete('/delete_chat')
def delete_chat(mes_id: int):
    mysql=MysqlLite()
    mysql.operation_sql('delete from history_message where ID=?',(mes_id,))
#根据

#用户退出
@router.delete('/logout')
def logout(username:str):
    online_users.remove(username)
#用户登录
@router.post('/add_online')
def add_online(username:str):
    online_users.append(username)
#在用户登录成功后查询是否有管理员信息
@router.get('/select_admin_mes')
def select_admin_mes(user_id:int):
    mysql=MysqlLite()
    result=[]
    id_lis=mysql.select_sql("""select ID from user_info where is_admin=1""")
    for i in id_lis:
        mes=mysql.select_sql("""select * from history_message where user_id1=? and user_id2=?""",(i[0],user_id))
        if mes:
            for j in mes:
                result.append(j)

    return {
        'code': 200,
        'data': result
    }


